package main

import "fmt"

/*
  组合模式
  例子：一个类 Employee，该类被当作组合模型类。CompositePatternDemo，我们的演示类使用 Employee 类来添加部门层次结构，并打印所有员工。
*/

// 组合零件
type Employee struct {
	id           int        //唯一id
	name         string     //名字
	dept         string     //部门
	salary       int        //薪酬
	subordinates []*Employee //下属
}

func (e *Employee) add(su *Employee) {
	e.subordinates = append(e.subordinates, su)

}

func (e *Employee) remove(su *Employee) {
	es := e.subordinates
	var index int
	for i, v := range es {
		if su.id == v.id {
			index = i
			break
		}
	}
	e.subordinates = append(es[:index], es[index+1:]...)
}

func (e *Employee) getSubordinates() []*Employee {
	return e.subordinates
}

func main() {
	ceo := Employee{id: 1, name: "John", dept: "CEO", salary: 30000}

	headSales := Employee{id: 2, name: "Robert", dept: "Head Sales", salary: 20000}
	headMarketing := Employee{id: 3, name: "Michel", dept: "Head Marketing", salary: 20000}

	clerk1 := Employee{id: 4, name: "Laura", dept: "Marketing", salary: 10000}
	clerk2 := Employee{id: 5, name: "Bob", dept: "Marketing", salary: 10000}

	salesExecutive1 := Employee{id: 6, name: "Richard", dept: "Sales", salary: 10000}
	salesExecutive2 := Employee{id: 7, name: "Rob", dept: "Sales", salary: 10000}

	ceo.add(&headSales)
	ceo.add(&headMarketing)
	headSales.add(&salesExecutive1)
	headSales.add(&salesExecutive2)
	headMarketing.add(&clerk1)
	headMarketing.add(&clerk2)

	//打印该组织的所有员工
	fmt.Println(&ceo)
	for _, headEmployee := range ceo.getSubordinates(){
		fmt.Println(headEmployee)
		for _, employee := range headEmployee.getSubordinates() {
			fmt.Println(employee)
		}
	}
}
